package cn.xmu.j2ee.exp.dao;

import cn.xmu.j2ee.exp.dao.bo.OrderItem;
import cn.xmu.j2ee.exp.dao.bo.Orders;
import cn.xmu.j2ee.exp.mapper.manual.OrdersMapper;
import cn.xmu.j2ee.exp.mapper.manual.po.OrdersPo;
import cn.xmu.j2ee.exp.util.BusinessException;
import cn.xmu.j2ee.exp.util.ReturnNo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import java.util.List;

import static cn.xmu.j2ee.exp.util.Common.*;

@Repository
public class OrdersDao {
    private final Logger logger = LoggerFactory.getLogger(OrdersDao.class);

    private final OrderItemDao orderItemDao;
    private final OrdersMapper ordersMapper;

    @Autowired
    public OrdersDao(OrdersMapper ordersMapper,OrderItemDao orderItemDao) {
        this.ordersMapper = ordersMapper;
        this.orderItemDao = orderItemDao;
    }

    /**
     * 用OrdersPo对象找Orders对象
     * @param  orderId 订单id
     * @return  Orders对象列表，带关联的Orders返回
     */
    public Orders findOrdersByID(Long orderId, boolean withOrderItemByDao) throws BusinessException {
        Orders orders = null;
        try{
            OrdersPo ordersPo = null;
            List<OrderItem> orderItemList=null;
            if (withOrderItemByDao) {
                ordersPo = ordersMapper.selectOrdersByOrderId(orderId);

            } else {
                ordersPo = ordersMapper.selectOrdersByOrderIdWithOrderItem(orderId);
                orderItemList=orderItemDao.retrieveOrderItemByOrderID(orderId);
            }
            logger.debug("findOrdersByID : ordersPo = {}", ordersPo);
            if (null == ordersPo){
                throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, "产品id不存在");
            }
            orders=cloneObj(ordersPo,Orders.class);
            if(orderItemList!=null)
                orders.setOrderItems(orderItemList);
            logger.debug("findOrdersByID: orders = {}",  orders);
        }
        catch(DataAccessException e){
            logger.error(e.getMessage());
            throw new BusinessException(ReturnNo.INTERNAL_SERVER_ERR, "数据库访问错误");
        }
        return orders;
    }
}
